package com.starblink.home.ui.adapter

import kotlinx.coroutines.*

object CoroutineUpdateHomeTask {
    private var scope: CoroutineScope? = null
    var taskTag: Boolean = false

    fun scheduleUpdate(interval: Long, action: () -> Unit) {
        if (taskTag) return
        taskTag = true
        cancelScope()
        val scope = CoroutineScope(Dispatchers.IO)
        scope.launch {
            while (isActive) {
                try {
                    action.invoke()
                } catch (e: Exception) {
                    e.printStackTrace()
//                    if (e is CancellationException) throw e
                }
                delay(interval)
            }
        }

        this.scope = scope
    }

    fun cancel() {
        scope?.cancel()
        scope = null
        taskTag = false
    }

    private fun cancelScope() {
        scope?.cancel()
        scope = null
    }

}